import { defineStore } from 'pinia'

import { accountLoginRequest, getUserInfoById } from '@/service/login.js'
import localCache from '@/utils/cache.js'
import { LOGIN_TOKEN } from '@/global/contants.js'
const useLoginStore = defineStore('login', {
	state: () => ({
		token: localCache.getCache(LOGIN_TOKEN) ?? '',
		userInfo: localCache.getCache('userInfo') ?? {}
	}),
	actions: {
		async loginAccountAction(account) {
			// 1.账号登录, 获取token等信息
			const loginResult = await accountLoginRequest(account)
			const id = loginResult.data.id
			this.token = loginResult.data.token
			
			const userInfoResult = await getUserInfoById(id)
			const userInfo = userInfoResult.data
			this.userInfo = userInfo
			this.userInfo.name = loginResult.data.name
	
			// 2.进行本地缓存
			localCache.setCache(LOGIN_TOKEN, this.token)
			// 4.进行本地缓存
			localCache.setCache('userInfo', userInfo)
		},
		async flushUserInfo(id) {
			const userInfoResult = await getUserInfoById(id)
			const userInfo = userInfoResult.data
			const name = this.userInfo.name
			this.userInfo = userInfo
			this.userInfo.name = name				
			// 4.进行本地缓存
			localCache.setCache('userInfo', userInfo)
		}
	}
})

export default useLoginStore
